package com.jianyun.jyzs.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jianyun.jyzs.MainActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.activity.FriendDetailActivity;
import com.jianyun.jyzs.adapter.ContactModuleFmAdapter;
import com.jianyun.jyzs.base.MVPBaseFragment;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.constant.ContactModuleFmHandler;
import com.jianyun.jyzs.dao.SysConfigDao;
import com.jianyun.jyzs.dao.UserDao;
import com.jianyun.jyzs.http.ContactModuleFmAsyncTask;
import com.jianyun.jyzs.http.ContactModuleFmAsyncTaskGet;
import com.jianyun.jyzs.http.ContactModuleFmBroadHelper;
import com.jianyun.jyzs.http.MainActHandler;
import com.jianyun.jyzs.presenter.ContactPresneter;
import com.jianyun.jyzs.receive.ContactModuleFmBroadCast;
import com.jianyun.jyzs.utils.AsyncTaskFmUtil;
import com.jianyun.jyzs.utils.FullDialogLoading;
import com.jianyun.jyzs.utils.HttpResultFmVO;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.utils.SysConstant2;
import com.jianyun.jyzs.view.iview.IContactFragmentView;
import com.jianyun.jyzs.widget.Sidebars;
import com.jrmf360.rylib.common.util.ToastUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;
import com.song.refresh_view.PullToRefreshView;

import net.sourceforge.pinyin4j.PinyinHelper;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.jrmf360.rylib.wallet.ui.BaseActivity.userId;


/**
 * *
 * @author 杨仕俊
 * @description 联系人  通讯录
 *              通讯录数据库重新输入
 * Created by yangshijun on 2018/5/25.
 */

public class ContactFragment extends MVPBaseFragment<IContactFragmentView, ContactPresneter> implements IContactFragmentView {


    @BindView(R.id.tv_loaing)
    TextView tvLoaing;
    @BindView(R.id.ll_loading)
    LinearLayout llLoading;
    @BindView(R.id.list)
    public SHListView listView;
    @BindView(R.id.sidebar)
    Sidebars sidebar;
    @BindView(R.id.floating_header)
    TextView floatingHeader;
    @BindView(R.id.rl_list)
    RelativeLayout rlList;
    @BindView(R.id.refreshView)
    SHSwipeRefreshLayout refreshView;

    private String enterpriseCode;
    public boolean isAginLoad = false;//是否重新加载
    private List<User> contactList;
    public MainActivity act;
    private ContactModuleFmAdapter adapter;
    public TextView tv_total;
    private FullDialogLoading dialog;
    private UserDao udao;
    private int total;
    private int cutPage;
    private boolean isNoMore = true;

    @Override
    public void onAttach(Activity activity) {
        act = (MainActivity) activity;
        super.onAttach(activity);
    }


    @Override
    protected void initView() {
        dialog = FullDialogLoading.createDialog(act);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setMessage(act.getString(R.string.load_text));
        refreshView.setRefreshEnable(true);
        refreshView.setLoadmoreEnable(true);
        View headView = LayoutInflater.from(act).inflate(R.layout.item_contact_list_header, null);
        View footerView = LayoutInflater.from(act).inflate(R.layout.item_contact_list_footer, null);
        tv_total = (TextView) footerView.findViewById(R.id.tv_total);
        listView.addFooterView(footerView);
        sidebar.setListView(listView);
        // 设置adapter
        contactList = new ArrayList<User>();
        adapter = new ContactModuleFmAdapter(act, R.layout.item_contact_list, contactList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("test", "po:" + position);
                Log.i("test", "size:" + contactList.size());
                if (position != contactList.size() + 1) {
                    if (position < contactList.size()) {
                        startActivity(new Intent(getActivity(), FriendDetailActivity.class).putExtra("serverUserId", contactList.get(position).getServerUserId()));

                    }

                }
            }
        });
    }

    @Override
    protected void initData() {
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        udao = new UserDao(getActivity());
        udao.deleteAllContact(enterpriseCode, userId);
        getPresenter().loadContact(enterpriseCode, userId, "1");
        if (contactList.size() > 10) {
            tv_total.setText(String.valueOf(contactList.size()) + "位联系人");
        } else {
            tv_total.setText("");
        }
        refreshView.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {
            @Override
            public void onRefresh() {
                contactList.clear();
                udao.deleteAllContact(enterpriseCode, userId);
                getPresenter().loadContact(enterpriseCode, userId, "1");
            }

            @Override
            public void onLoading() {
                Log.i("test", "cutPage:" + cutPage + "\n" + "total:" + total);

                if (isNoMore) {
                    contactList.clear();
                    int tmep = cutPage + 5;
                    Log.i("ysj", "请求：" + tmep);
                    getPresenter().getMoreContact(enterpriseCode, userId, cutPage, tmep);
                } else {
                    ToastUtil.showToast(getActivity(), "没有更多数据！");
                    //refreshView.setLoadmoreEnable(isNoMore);
                    refreshView.finishLoadmore();
                }
            }

            @Override
            public void onRefreshPulStateChange(float v, int i) {

            }

            @Override
            public void onLoadmorePullStateChange(float v, int i) {

            }

        });
    }


    @Override
    protected int initContentLayout() {
        isAginLoad = true;
        return R.layout.fragment_contact_module;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            return;
        }
        if (isAginLoad) {
            isAginLoad = false;
        }
        if (!act.isSynchContact) {

        } else {
            Toast.makeText(act.getApplicationContext(), "请稍后,正在获取通讯录数据...", Toast.LENGTH_SHORT).show();
        }


    }


    @Override
    public void onResume() {
        super.onResume();
    }


    Handler mhandlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 1) {
                // 对list进行排序
                Collections.sort(contactList, new PinyinComparator() {
                });
                adapter.notifyDataSetInvalidated();
                tv_total.setText(String.valueOf(contactList.size()) + "位联系人");
                //refreshView.setRefreshing(false);
                refreshView.finishRefresh();
                refreshView.finishLoadmore();
                if (dialog != null && dialog.isShowing()) {

                    dialog.dismiss();
                    //List<User> users = udao.queryConstants(enterpriseCode, userId);
                    //Log.i("test","数据库查询："+users.size());
                }
                act.isSynchContact = false;
            }
        }
    };

    /**
     * 获取联系人列表--排序
     */
    @SuppressLint("DefaultLocale")
    public void processContactList(final List<User> userslist) {
        try {
            final int size = userslist.size();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    User user = null;
                    for (int i = 0; i < size; i++) {
                        user = userslist.get(i);
                        udao.insert(user);
                        if (Character.isDigit(user.getNameZh().charAt(0))) {
                            user.setHeader("#");
                        } else {
                            user.setHeader(getFirstChar(user.getNameZh()));
                            char header = user.getHeader().toLowerCase().charAt(0);
                            if (header < 'a' || header > 'z') {
                                user.setHeader("#");
                            }
                        }
                        contactList.add(user);
                    }
                    Message message = new Message();
                    message.arg1 = 1;
                    message.obj = contactList;
                    mhandlers.sendMessage(message);
                }
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void hintLoading() {
        dialog.show();
    }

    @Override
    public void loadContactSuccess(List<User> userList) {
        //this.contactList=userList;
        Log.i("test", "界面：" + userList.size());
        processContactList(userList);
    }

    @Override
    public void setPageCut(int total, int pageIndex) {

        this.total = total;
        this.cutPage = pageIndex;
        Log.i("ysj", "数目：" + total + "\n" + "cutPage:" + pageIndex);
    }

    @Override
    public void loadFailed(String msg) {
        dialog.dismiss();
        refreshView.finishRefresh();
        refreshView.finishLoadmore();
        ToastUtil.showToast(getActivity(), msg);
    }

    @Override
    public void onLoadMore(boolean isMore) {
        this.isNoMore = isMore;


    }


    @SuppressLint("DefaultLocale")
    public class PinyinComparator implements Comparator<User> {
        @SuppressLint("DefaultLocale")
        @Override
        public int compare(User o1, User o2) {
            String py1 = o1.getHeader();
            String py2 = o2.getHeader();
            // 判断是否为空""
            if (isEmpty(py1) && isEmpty(py2))
                return 0;
            if (isEmpty(py1))
                return -1;
            if (isEmpty(py2))
                return 1;
            String str1 = "";
            String str2 = "";
            try {
                str1 = ((o1.getHeader()).toUpperCase()).substring(0, 1);
                str2 = ((o2.getHeader()).toUpperCase()).substring(0, 1);
            } catch (Exception e) {
                System.out.println("某个str为\" \" 空");
            }
            return str1.compareTo(str2);
        }

        private boolean isEmpty(String str) {
            return "".equals(str.trim());
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public ContactPresneter createPresenter() {
        return new ContactPresneter();
    }


    //获得字符串的首字母 首字符 转汉语拼音
    public static String getFirstChar(String value) {
        String first = "#";// 首字母分类
        if (value == null || value.trim().equals("")) {
            return first;
        }
        char firstChar = value.charAt(0);// 首字符
        String[] print = PinyinHelper.toHanyuPinyinStringArray(firstChar);// 是否是非汉字

        if (print == null) {
            // 将小写字母改成大写
            if ((firstChar >= 97 && firstChar <= 122)) {
                firstChar -= 32;
            }
            if (firstChar >= 65 && firstChar <= 90) {
                first = String.valueOf((char) firstChar);
            } else {// 认为首字符为数字或者特殊字符
                first = "#";
            }
        } else {// 如果是中文 分类大写字母
            first = String.valueOf((char) (print[0].charAt(0) - 32));
        }
        return first;
    }


}
